import { ActionType, ProFormText, ProFormTextArea, StepsForm } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { message, Modal, Tree, TreeDataNode, TreeProps } from 'antd';
import { cloneElement, useCallback, useState } from 'react';
import { dataResponse, detailRequest, roleDetailResponse } from '../data';
import { createRole, queryRole, updateRole } from '../service';

interface EditFormProps {
  reload?: ActionType['reload'];
  values?: Partial<dataResponse>;
  trigger?: JSX.Element;
  treeList: TreeDataNode[];
}

const EditForm: React.FC<EditFormProps> = (props) => {
  const { reload, values, trigger, treeList } = props;
  const [open, setOpen] = useState(false);
  const [roleInfo, setroleInfo] = useState<roleDetailResponse>();
  const [messageApi, contextHolder] = message.useMessage();
  /* const intl = useIntl(); */
  /* const [treeData, setTreeList] = useState<TreeDataNode[]>([]); */
  //树方法
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    console.log(checkedKeysValue)
    setCheckedKeys(checkedKeysValue as string[]);
  };
  const onSelect: TreeProps['onSelect'] = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue as string[]);
  };
  const getRolePermission = async () => {
    if (values) {
      const param: detailRequest = {
        code: values.code!,
      };
      const data = await queryRole(param);
      console.log(data,1231231313)
      if (data.success && data.result) {
        setroleInfo(data.result);
        setCheckedKeys(data.result.permissionCodeList!);
      }
    }
  };

  const onCancel = useCallback(() => {
    setOpen(false);
  }, []);

  const onOpen = useCallback(async () => {
    await getRolePermission();
    setOpen(true);
  }, []);

  const { run } = useRequest(values ? updateRole : createRole, {
    manual: true,
    onSuccess: () => {
      messageApi.success('操作成功！');
      reload?.();
      onCancel();
    },
    onError: () => {
      messageApi.error('操作失败，请重试！');
      onOpen();
    },
  });

  return (
    <>
      {contextHolder}
      {trigger
        ? cloneElement(trigger, {
            onClick: onOpen,
          })
        : null}
      <StepsForm
        stepsProps={{
          size: 'small',
        }}
        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              width={640}
              styles={{
                body: { padding: '32px 40px 48px' },
              }}
              destroyOnClose
              title={values ? '修改角色' : '新建角色'}
              open={open}
              footer={submitter}
              onCancel={onCancel}
            >
              {dom}
            </Modal>
          );
        }}
        onFinish={async (value) => {
          await run({
            code: roleInfo?.code,
            name: value.name!,
            description: value.description!,
            permissionCodeList: checkedKeys,
            /* areaCodeList: roleInfo!.areaList!, */
          });
          onCancel();
          return true;
        }}
      >
        <StepsForm.StepForm
          initialValues={roleInfo}
          title='基本信息'
        >
          <ProFormText
            name="name"
            label="角色名称"
            width="md"
            rules={[
              {
                required: true,
                message:"请输入！",
              },
            ]}
          />
          <ProFormTextArea
            name="description"
            width="md"
            label="角色描述"
            placeholder="请输入！"
          />
        </StepsForm.StepForm>
        <StepsForm.StepForm
          initialValues={{
            target: '0',
            template: '0',
          }}
          title="配置角色权限"
        >
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={treeList}
          />
        </StepsForm.StepForm>
      </StepsForm>
    </>
  );
};

export default EditForm;
